package com.sihai.ehr.service.impl;

import com.sihai.core.*;
import com.sihai.core.support.HibernateDataAccessor;
import com.sihai.ehr.model.biz.*;
import com.sihai.ehr.model.sys.AuditStatus;
import com.sihai.ehr.model.sys.ExaminePeriodEnum;
import com.sihai.ehr.model.sys.Organization;
import com.sihai.ehr.model.sys.User;
import com.sihai.ehr.service.ExamQuanDataInputService;
import com.sihai.ehr.utils.PeriodUtils;
import com.sihai.ehr.web.pojo.ExamDataInputPojo;
import org.apache.commons.lang.xwork.StringUtils;
import org.hibernate.Query;
import org.hibernate.Session;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.Statement;
import java.util.*;

/**
 * @author :zj
 */

@Service("examQuanDataInputService")
public class ExamQuanInputServiceImpl implements ExamQuanDataInputService {

    @Resource
    private DataAccessor dataAccessor;

    @Override
    public LimitedList<ExamDataInputPojo> searchExamQuanScores(final Long organizationId, final Long dutyId, final ExaminePeriodEnum periodType, final Long period, final int status, Limit limit, Sorter sorter) {
        try {
            Organization organization = null;
            boolean isReadTopOrg = false;
            if (organizationId > 0) {
                try {
                    organization = dataAccessor.get(Organization.class,
                            organizationId);
                    if (organization.getTopOrganization() == null) {
                        isReadTopOrg = true;
                    }
                } catch (Exception e) {
                    return null;
                }
            }

            final boolean isReadTopOrganization = isReadTopOrg;
            return dataAccessor.findByQuery(ExamDataInputPojo.class,
                    new QueryCreator() {

                        @Override
                        public Query createQuery(Session session) {
                            // right join i.employeeinfoWork
                            DynamicQuery dynamicQuery = new DynamicQuery(
                                    "select new com.sihai.ehr.web.pojo.ExamDataInputPojo(e.id,w.id,w.duty.id,w.baseId.name,w.organization.fullName,w.duty.dutyName,w.grade.gradeName) from ExamQuanScore e right join e.employeeinfoWork w where w.cancel<>1");

                            if (isReadTopOrganization) {
                                dynamicQuery
                                        .appendIfNotNull(
                                                "and (w.organization.topOrganization.id=:organization_id or w.organization.id =:organization_id)",
                                                "organization_id",
                                                organizationId);
                            } else if (organizationId > 0) {
                                dynamicQuery
                                        .appendIfNotNull(
                                                "and w.organization.id =:organization_id",
                                                "organization_id",
                                                organizationId);
                            }
                            if (dutyId > 0) {
                                dynamicQuery.appendIfNotNull(
                                        "and w.duty.id =:duty_id", "duty_id",
                                        dutyId);
                            }
                            dynamicQuery.appendIfNotNull(
                                    "and e.examPeriod.periodType =:periodType",
                                    "periodType", periodType);

                            if (status > 0) {
                                dynamicQuery.append("and e.status =:status",
                                        "status", status);
                            } else {
                                dynamicQuery.append("and e.status is null");    //表示未打分
                            }
                            return dynamicQuery.build(session);
                        }
                    }, limit, sorter);
        } catch (Exception e) {
            throw new RuntimeException(
                    "【异常原因：获取定量考核打分对象集合时数据库发生异常】【异常说明：+"
                            + e.getMessage()
                            + "】【发生地点：ExamQuanInputServiceImpl.searchExamQuanScores;参数organizationId="
                            + organizationId + ",periodType=" + periodType
                            + "】");
        }
    }

    @Override
    public LimitedList<ExamQuanItemSet> findExamQuanItemSetByDuty(Long dutyId,Limit limit,Sorter sorter) {
        if(dutyId==null){
            return null;
        }
        return dataAccessor.findByHql(ExamQuanItemSet.class,"select new ExamQuanItemSet(e.id,e.title,e.percentage,e.remark,e.periodType) from ExamQuanItemSet e right join e.examQuanSet s where s.duty.id=?",new Object[]{dutyId},limit,sorter);
    }

    /**
     * create wxn
     * 查询定量数据输入界面中的未输入数据列表(按员工列表)
     */
    @Override
    public LimitedList<EmployeeinfoWork> searchExamQuanUnInputs(final Long organizationId, final ExamEmbedPeriod examPeriod, Limit limit, Sorter sorter) {
        try {
            //配置过项目的职务列表
            final List<Long> dutyIds = dataAccessor.findByQuery(Long.class,
                    new QueryCreator() {
                        @Override
                        public Query createQuery(Session session) {
                            DynamicQuery dynamicQuery = new DynamicQuery("select distinct(eis.examQuanSet.duty.id) from ExamQuanItemSet eis where 1=1");
                            dynamicQuery.appendIfNotNull("and eis.periodType = :periodType", "periodType", examPeriod.getPeriodType());
                            dynamicQuery.appendIfNotNull("and eis.examQuanSet.duty.organization.id = :organizationId", "organizationId", organizationId);
                            //TODO:添加ExamQuanItemSet的输入人或输入职务为当前登录用户
                            return dynamicQuery.build(session);
                        }
                    }, null, null);
            if(dutyIds == null || dutyIds.isEmpty()){
                return null;
            }

            //已输入的用户id
            final List<Long> workIds = (examPeriod == null ? null : dataAccessor.findByHql(Long.class, "select distinct(esd.employeeinfoWork.id) from ExamQuanScoreDetail esd where esd.embedPeriod.periodType = ? and esd.embedPeriod.periodName = ?", new Object[]{examPeriod.getPeriodType(), examPeriod.getPeriodName()}, null, null));

            return dataAccessor.findByQuery(EmployeeinfoWork.class,
                    new QueryCreator() {
                        @Override
                        public Query createQuery(Session session) {
                            DynamicQuery dynamicQuery = new DynamicQuery("from EmployeeinfoWork w where 1=1");
                            dynamicQuery.appendIfNotNull("and w.duty.id in (:dutyIds)", "dutyIds", dutyIds);
                            if(workIds != null && !workIds.isEmpty()){
                                dynamicQuery.append("and w.id not in (:workIds)", "workIds", workIds);
                            }
                            return dynamicQuery.build(session);
                        }
                    }, limit, sorter);
        } catch (Exception e) {
            e.printStackTrace();
            throw new RuntimeException(e.getMessage());
        }
    }

    /**
     * create wxn
     * 查询定量数据输入界面中的未输入数据列表(按定量测试项目item列表)
     */
    @Override
    public LimitedList<EmployeeinfoWork> searchExamQuanUnInputsByItems(User currentUser, final Long organizationId, final ExamEmbedPeriod examPeriod, Limit limit, Sorter sorter) {
        try {
            //建构limit条件
            if(limit == null){
                limit = new Limit(0, 10);
            }
            String limitStr = String.format(" limit %s, %s", limit.getOffset(), limit.getCount());

            String treePath = "";
            if(organizationId != null){
                Organization organization = dataAccessor.get(Organization.class, organizationId);
                if(organization != null){
                    treePath = organization.getTreePath();
                }
            }

            //查找条件中添加项目输入人是当前登录的用户
            long wid = currentUser.getWork().getId().longValue();
            long did = currentUser.getWork().getDuty().getId().longValue();
            String inputerWhere = String.format("and ((i.data_entier_type=1 and i.input_employee_id=%s) or (i.data_entier_type=2 and i.input_duty_id=%s))", wid, did);

            //String orgWhere = organizationId == null ? "" : "and w.organization_id="+organizationId.longValue();
            String orgWhere = organizationId == null ? "" : "and w.organization_id in (select id from organization where tree_path like '"+treePath+"%')";
            String temp = String.format("from exam_quan_item_set i, employeeinfo_work w  where i.period_type='%s' %s "+inputerWhere+" and i.duty_id = w.duty_id and (i.id, w.id) not in (select d.examitem_id, d.work_id from exam_quan_score_detail d where d.period_type='%s' and d.period_name='%s') order by w.id", examPeriod.getPeriodType().toString(), orgWhere, examPeriod.getPeriodType().toString(), examPeriod.getPeriodName());
            //String sql = "SELECT w.id,e.id,i.id FROM exam_quan_set e, exam_quan_item_set i, employeeinfo_work w where e.duty_id = w.duty_id and i.examquanset_id = e.id group by w.id,e.id,i.id having w.id not in (1,2) or i.id not in(12,5)";
            String sql_count = "select count(1) " + temp;
            String sql = "select w.id as work_id, i.id as item_id, w.duty_id as duty_id " + temp;
            System.out.println("wxn---sql:"+sql);
            Connection connection = ((HibernateDataAccessor) dataAccessor).getHibernateTemplate().getSessionFactory().getCurrentSession().connection();
            Statement statement = connection.createStatement();
            //查总个数
            ResultSet rs = statement.executeQuery(sql_count);
            //rs.last();//称到最后一行，并得到行号，即为rs的长度
            //int rowSize = rs.getRow();
            rs.first();
            int rowSize = rs.getInt(1);
            LimitedList<EmployeeinfoWork> limitedList = new LimitedList<EmployeeinfoWork>();
            limitedList.setTotalcount(rowSize);
            //查指定页
            rs = statement.executeQuery(sql+limitStr);
            while(rs.next()){
                Long workId = rs.getLong(1);
                //Long setId = rs.getLong(2);
                //Long itemId = rs.getLong(3);
                EmployeeinfoWork work = dataAccessor.get(EmployeeinfoWork.class, workId);
                limitedList.add(work);
            }
            rs.close();
            statement.close();
            connection.close();

            return limitedList;

        } catch (Exception e) {
            e.printStackTrace();
            throw new RuntimeException(e.getMessage());
        }
    }


    //输入列表(ExamQuanScoreDetail不存在时)
    public List<ExamQuanItemSet> findExamQuanItemSetForInput(User currentUser, Long dutyId, ExaminePeriodEnum periodEnum, Limit limit, Sorter sorter){
        try {
            return dataAccessor.findByHql(ExamQuanItemSet.class, "from ExamQuanItemSet eqis where eqis.periodType = ? and eqis.examQuanSet.duty.id = ? and ((eqis.dataEntierType=1 and eqis.dataEntrier=?) or (eqis.dataEntierType=2 and eqis.dataEntryDuty=?))", new Object[]{periodEnum, dutyId, currentUser.getWork(), currentUser.getWork().getDuty()}, limit, sorter);
        }catch (Exception e) {
            throw new RuntimeException(e.getMessage());
        }
    }

    @Override
    public ExamQuanItemSet getExamQuanItemSet(Long id) {
        if(id == null){
            return null;
        }
        return dataAccessor.get(ExamQuanItemSet.class, id);
    }

    @Override
    public ExamQuanScoreDetail getExamQuanScoreDetail(Long id) {
        if(id == null){
            return null;
        }
        return dataAccessor.get(ExamQuanScoreDetail.class, id);
    }

    //添加或更新数据输入
    @Override
    public void saveDateInputs(List<ExamQuanScoreDetail> scoreDetails) {
        if(scoreDetails == null || scoreDetails.isEmpty()){
            return;
        }
        for(ExamQuanScoreDetail detail : scoreDetails){
            dataAccessor.save(detail);
        }
    }

    //按周期类型统计考核项目数
    @Override
    public Long totalQuanItems(final ExaminePeriodEnum periodEnum, final Long organizationId) {
        return this.dataAccessor.findUnique(Long.class, new QueryCreator() {
            @Override
            public Query createQuery(Session session) {
                DynamicQuery query = new DynamicQuery("select count(eis.id) from ExamQuanItemSet eis where 1=1");
                query.appendIfNotNull("and eis.periodType=:periodEnum", "periodEnum", periodEnum);
                if(organizationId != null && organizationId > 0){
                    query.append("and eis.examQuanSet.duty.organization.id=:organizationId", "organizationId", organizationId);
                }
                return query.build(session);
            }
        });
    }

    //按状态+周期类型+周期+部门统计已输入的考核项目数
    @Override
    public Long totalQuanDetails(final ExamEmbedPeriod embedPeriod, final AuditStatus status, final Long organizationId) {
        return this.dataAccessor.findUnique(Long.class, new QueryCreator() {
            @Override
            public Query createQuery(Session session) {
                DynamicQuery query = new DynamicQuery("select count(esd.id) from ExamQuanScoreDetail esd where 1=1");
                query.appendIfNotNull("and esd.examQuanScore.embedPeriod.periodType=:periodEnum", "periodEnum", embedPeriod.getPeriodType());
                query.appendIfNotNull("and esd.examQuanScore.embedPeriod.periodName=:periodName", "periodName", embedPeriod.getPeriodName());
                //query.appendIfNotNull("and esd.examQuanScore.embedPeriod=:embedPeriod", "embedPeriod", embedPeriod);
                query.appendIfNotNull("and esd.examQuanScore.status=:status", "status", status);
                if(organizationId != null && organizationId > 0){
                    query.append("and eis.examQuanSet.duty.organization.id=:organizationId", "organizationId", organizationId);
                }
                return query.build(session);
            }
        });
    }

    @Override
    public LimitedList<ExamQuanScoreDetail> searchExamQuanDetails(final String type, final User currentUser, final Long organizationId, final Long workId, final ExamEmbedPeriod embedPeriod, final AuditStatus status, Limit limit, Sorter sorter) {
        try {
            return dataAccessor.findByQuery(ExamQuanScoreDetail.class,
                    new QueryCreator() {
                        @Override
                        public Query createQuery(Session session) {
                            DynamicQuery dynamicQuery = new DynamicQuery("from ExamQuanScoreDetail esd where 1=1");
                            if(organizationId != null && organizationId > 0){
                                //dynamicQuery.append("and esd.employeeinfoWork.organization.id = :organizationId", "organizationId", organizationId);
                                Organization organization = dataAccessor.get(Organization.class, organizationId);
                                dynamicQuery.append("and esd.employeeinfoWork.organization.treePath like '"+organization.getTreePath()+"%'");
                            }
                            if(workId != null && workId > 0){
                                dynamicQuery.append("and esd.employeeinfoWork.id = :workId", "workId", workId);
                            }
                            dynamicQuery.appendIfNotNull("and esd.embedPeriod.periodType = :periodType", "periodType", embedPeriod.getPeriodType());
                            dynamicQuery.appendIfNotNull("and esd.embedPeriod.periodName = :periodName", "periodName", embedPeriod.getPeriodName());
                            if(status == AuditStatus.reject_audit){
                                dynamicQuery.append("and esd.status = :status and esd.rejectTimes > 0", "status", AuditStatus.wait_audit);
                            }else if(status == AuditStatus.wait_audit){
                                dynamicQuery.append("and esd.status = :status and esd.rejectTimes = 0", "status", AuditStatus.wait_audit);
                            }else if(status == AuditStatus.within_audit){
                                dynamicQuery.append("and esd.status = :status", "status", AuditStatus.wait_audit);
                            }else{
                                dynamicQuery.appendIfNotNull("and esd.status = :status", "status", status);
                            }
                            if(StringUtils.equals("input", type)){
                                dynamicQuery.append("and (");
                                dynamicQuery.appendIfNotNull("(esd.examQuanItemSet.dataEntierType=1 and esd.examQuanItemSet.dataEntrier=:dataEntrier)", "dataEntrier", currentUser.getWork());
                                dynamicQuery.appendIfNotNull("or (esd.examQuanItemSet.dataEntierType=2 and esd.examQuanItemSet.dataEntryDuty=:dataEntryDuty)", "dataEntryDuty", currentUser.getWork().getDuty());
                                dynamicQuery.append(")");
                            }else if (StringUtils.equals("audit", type)){
                                dynamicQuery.append("and (");
                                dynamicQuery.appendIfNotNull("(esd.examQuanItemSet.dataAuditerType=1 and esd.examQuanItemSet.dataAuditer=:dataAuditer)", "dataAuditer", currentUser.getWork());
                                dynamicQuery.appendIfNotNull("or (esd.examQuanItemSet.dataAuditerType=2 and esd.examQuanItemSet.dataAuditDuty=:dataAuditDuty)", "dataAuditDuty", currentUser.getWork().getDuty());
                                dynamicQuery.append(")");
                            }

                            return dynamicQuery.build(session);
                        }
                    }, limit, sorter);
        }catch (Exception e) {
            throw new RuntimeException(e.getMessage());
        }
    }

    //审核
    @Override
    public void saveQuanAuditing(ExamQuanScoreAuditing audit) {
        if(audit == null){
            return;
        }
        dataAccessor.save(audit);
        if(audit.getStatus() == AuditStatus.pass_audit){
            final ExamQuanScoreDetail detail = audit.getExamQuanScoreDetail();
            detail.setStatus(AuditStatus.pass_audit);
            dataAccessor.save(detail);

            /**
             * 判断是否入统计表：
             * 方法一：本次审核的对象是否是大周期中的最后一个小周期,如果是,则该大周期考核完毕,定量数据入统计表
             * 方法二：判断总的审核次数是否为大周期内配置的项目总的考核次数
             */
            //查找某一员工某一大周期内考核通过的项目数
            //Long count = dataAccessor.findUnique(Long.class, new QueryCreator() {
            List<ExamQuanScoreDetail> details = dataAccessor.findByQuery(ExamQuanScoreDetail.class, new QueryCreator() {
                @Override
                public Query createQuery(Session session) {
                    Query query = session.createQuery("from ExamQuanScoreDetail d where d.examQuanItemSet.examQuanSet.id=:setId and d.status=:status and d.employeeinfoWork.id=:workId and d.examPeriod.id=:examPeriodId");
                    query.setParameter("setId", detail.getExamQuanItemSet().getExamQuanSet().getId());
                    query.setParameter("status", AuditStatus.pass_audit);
                    query.setParameter("workId", detail.getEmployeeinfoWork().getId());
                    query.setParameter("examPeriodId", detail.getExamPeriod().getId());
                    return query;
                }
            }, null, null);
            int count = (details == null ? 0 : details.size());
            ExaminePeriodEnum maxPeriod = detail.getExamPeriod().getPeriodType(); //大周期
            int max = PeriodUtils.getCountByPeriodType(maxPeriod);
            if(count < max){
                return;
            }
            List<Object[]> list = dataAccessor.findByHql(Object[].class, "select count(i.id), i.periodType from ExamQuanItemSet i where i.examQuanSet.id = ? group by i.periodType", new Object[]{detail.getExamQuanItemSet().getExamQuanSet().getId()},null,null);
            if(list != null && list.size() > 0){
                int total = 0;
                for(Object[] objects : list){
                    Long c = (Long)objects[0];
                    ExaminePeriodEnum period = (ExaminePeriodEnum)objects[1];
                    int min = PeriodUtils.getCountByPeriodType(period);
                    total += (max/min) * c;
                }
                //审核完成数等于总的需要审核的次数,则入统计表
                if (total == count) {
                    //计算定量部分总分(key为d.examQuanItemSet.id, value为该item对应的各小同期得分列表)
                    Map<Long, ArrayList<Float>> map = new HashMap<Long, ArrayList<Float>>();
                    for(ExamQuanScoreDetail d : details){
                        Long itemId = d.getExamQuanItemSet().getId();
                        ArrayList<Float> scores = null;
                        if(map.containsKey(itemId)){
                            scores = map.get(itemId);
                        }else{
                            scores = new ArrayList<Float>();
                        }
                        scores.add(d.getScore()*d.getExamQuanItemSet().getPercentage()/100);//分数*百分比
                        map.put(itemId, scores);
                    }
                    float score = 0; //定量得分
                    Set<Long> keys = map.keySet();
                    for(Long key : keys){
                        float pscore = 0.0f;
                        ArrayList<Float> scores = map.get(key);
                        for(Float s : scores){
                            pscore += s;
                        }
                        score += pscore/scores.size();
                    }

                    //入统计表
                    List<ExamStatistics> statisticses = dataAccessor.findByHql(ExamStatistics.class, "from ExamStatistics s where s.examPeriod.id=? and s.employeeinfoWork.id=?", new Object[]{detail.getExamPeriod().getId(), detail.getEmployeeinfoWork().getId()}, null, null);
                    Float prevScore = prevScore(detail.getEmployeeinfoWork().getId(), detail.getExamPeriod().getPeriodType());
                    ExamStatistics statistics = null;
                    //定性部分已打分
                    if(statisticses != null && !statisticses.isEmpty()){
                        statistics = statisticses.get(0);
                        statistics.setQuanScore(score);
                        //总分
                        Float scoreFloat = (statistics.getQualScore() * statistics.getExamBaseConfig().getPercentageQualitative()
                                + score * statistics.getExamBaseConfig().getPercentageQuantitative())/100;
                        statistics.setScore(scoreFloat);
                        statistics.setPrevScore(prevScore == null || prevScore <= 0 ? scoreFloat : prevScore);
                    }else{//定性部分还没打分
                        statistics = new ExamStatistics();
                        List<ExamBaseConfig> configs = dataAccessor.findByHql(ExamBaseConfig.class, "from ExamBaseConfig e where e.duty.id=?", new Object[]{detail.getExamQuanItemSet().getDuty().getId()}, null, null);
                        if(configs == null || configs.isEmpty()){
                            return;
                        }
                        statistics.setExamBaseConfig(configs.get(0));
                        statistics.setEmployeeinfoWork(detail.getEmployeeinfoWork());
                        statistics.setExamPeriod(detail.getExamPeriod());
                        statistics.setQuanScore(score);
                    }
                    //如果定性比例为0，则总分即为定量部分的分数
                    Float qualPercent = statistics.getExamBaseConfig().getPercentageQualitative();
                    if(qualPercent == null || qualPercent.longValue() <= 0){
                        statistics.setScore(score);
                        statistics.setPrevScore(prevScore == null || prevScore <= 0 ? score : prevScore);
                    }

                    dataAccessor.save(statistics);

                }
            }
        }else if(audit.getStatus() == AuditStatus.reject_audit){
            ExamQuanScoreDetail detail = audit.getExamQuanScoreDetail();
            detail.setRejectTimes(detail.getRejectTimes()+1);
            dataAccessor.save(detail);
        }
    }

    @Override
    public List<ExamQuanScoreAuditing> findExamQuanScoreAudits(Long quanScoreDetailId) {
        return dataAccessor.findByHql(ExamQuanScoreAuditing.class, "from ExamQuanScoreAuditing qsa where examQuanScoreDetail.id = ? order by create_date asc", new Object[]{quanScoreDetailId}, null, null);
    }

    @Override
    public LimitedList<ExamQuanScoreDetail> findExamQuanScoreDetails(Long workId, String year, Long itemId, Limit limit, Sorter sorter) {
        return dataAccessor.findByHql(ExamQuanScoreDetail.class, "from ExamQuanScoreDetail sd where sd.employeeinfoWork.id=? and sd.examQuanItemSet.id=? and sd.embedPeriod.periodName like '"+year+"%'", new Object[]{workId, itemId}, null, null);
    }

    @Override
    public List<ExamQuanScoreDetail> findExamQuanScoreDetails(Long workId, Long periodId) {
        return dataAccessor.findByHql(ExamQuanScoreDetail.class, "from ExamQuanScoreDetail d where d.employeeinfoWork.id=? and examPeriod.id = ? order by d.id", new Object[]{workId, periodId}, null, null);
    }

    @Override
    public boolean submitCheck(ExamEmbedPeriod period, User loginUser) {
        //List<Long> list = dataAccessor.findByHql(Long.class, "select id from ExamQuanInputSubmitLog where embedPeriod.periodType=? and embedPeriod.periodName=? and inputter is not null and inputter.id = ?", new Object[]{period.getPeriodType(), period.getPeriodName(), loginUser.getId()}, null, null);
        //test
        List<Long> list = dataAccessor.findByHql(Long.class, "select id from ExamQuanInputSubmitLog where embedPeriod.periodType=? and embedPeriod.periodName=?", new Object[]{period.getPeriodType(), period.getPeriodName()}, null, null);
        return  (list != null && !list.isEmpty());
    }

    @Override
    public boolean submitInput(final ExamEmbedPeriod period, final User loginUser) {
        if(loginUser == null || loginUser.getId() == null){
            return false;
        }
        final List<ExamQuanScoreDetail> details = dataAccessor.findByHql(ExamQuanScoreDetail.class, "from ExamQuanScoreDetail d where d.status = ? and ((d.examQuanItemSet.dataEntierType=1 and d.examQuanItemSet.dataEntrier.id=?) or (d.examQuanItemSet.dataEntierType=2 and d.examQuanItemSet.dataEntryDuty.id=?)) and d.embedPeriod.periodType=? and d.embedPeriod.periodName=?", new Object[]{AuditStatus.wait_submit, loginUser.getWork().getId(), loginUser.getWork().getDuty().getId(), period.getPeriodType(), period.getPeriodName()}, null, null);
        if(details == null || details.isEmpty()){
            return true;
        }
        for(ExamQuanScoreDetail d : details){
            d.setStatus(AuditStatus.wait_audit);
            dataAccessor.save(d);
        }
        return true;
    }

    @Override
    public Float prevScore(Long workId, ExaminePeriodEnum examPeriodEnum) {
        List<Float> list = dataAccessor.findByHql(Float.class, "select s.score from ExamStatistics s where s.employeeinfoWork.id = ? and s.examPeriod.periodType = ? order by s.examPeriod.examYear desc, s.examPeriod.examMonthly desc limit 0, 1", new Object[]{workId, examPeriodEnum}, null, null);
        if(list != null && !list.isEmpty()){
            return list.get(0);
        }
        return null;
    }
}
